package com.yshebkb.sulp.config;

import com.yshebkb.sulp.dao.UserMapper;
import com.yshebkb.sulp.entity.User;
import com.yshebkb.sulp.service.UserService;
import com.yshebkb.sulp.utils.ShiroUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author yshebkb
 */
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Subject subject = ShiroUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Long userId = user.getId();
        // 获取用户权限
        Set<String> permsSet = userService.getPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 将权限加入到用户的信息中
        info.addStringPermissions(permsSet);
        return info;
    }

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        //查询用户信息
        User user = userMapper.findByName(username);
        ShiroUtils.getSession().setAttribute("user", user);
        //账号不存在
        if (user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

}
